'use strict';
/*
 * @zdy: 新建上报 发送失败,点击重发
 */

//初始化方法
YX.fn.zdy_m_new_handUp = function() {
	this.$btnNewHandUp = $("#btn-new-handup")
	this.$btnNewHandUp.on('click', this.newHandUp.bind(this))
	this.$mNextStep = $("#m-nextStep")
	this.$mNextStep.on('click', this.nextStep.bind(this))
	this.$sendtestBtn = $("#sendtestBtn")
	this.$sendtestBtn.on('click', this.zdyPerson.bind(this))
		//下一步注册事件
		$("body").on('click', "#m-lastStep", this.lastStep.bind(this))
		//确定新建注册事件
		$("body").on('click', "#new-HandUp-Sure", this.newHandUpSubmit.bind(this))

	//加keycode监听事件
	$("body").on("keydown", this.zdyKeyEvent.bind(this))
	
	//点击@提示
	$("body").on("click","#zdy-a-me-tips",this.scrollToame.bind(this))
	

}


YX.fn.scrollToame = function(){
	let idClient =  $("#zdy-a-me-tips").data("idclient")
	$("#chatContent").mCustomScrollbar('scrollTo',"#"+idClient)
	this.ame = ""
	$("#zdy-a-me-tips").hide()
}

YX.fn.zdyKeyEvent = function(event) {
	event = window.event || event
	var key = event.keyCode || event.which

	if($("#person-ul").is(":visible")) {
		if(key == 37) {
			//alert("按了←键！")
			if(e && e.stopPropagation) e.stopPropagation();
			else e.cancelBubble = true
				if(e && e.preventDefault) e.preventDefault();
			else e.returnValue = false
				return false;
		};
		if(key == 38) {
			alert("按了↑键！")
		};
		if(key == 39) {
			//alert("按了→键！")
			return false;
		};
		if(key == 40) {
			alert("按了↓键！")
		};
	}

}

//下一步
YX.fn.nextStep = function() {
	var that = this
	if($("input[name='mnOrg']:checked").length < 1) {
		$("#mn-step01-remind").removeClass("hideDiv");
		return false;
	}

	if($("#m-new-handUp_step02").html() !== "") {
		Modal.hide("#m-new-handUp_step01", function() {
			Modal.show("#m-new-handUp_step02");
		});
		return;
	}
	$("#m-new-handUp_step02").load("../zdy-view/newhandUp_step02.html", function() {
		var mnPlansUl = $("#mn-plan-ul");
		var OLi = "";

		var CurrentClient = getCurrentClient(),
		plans = CurrentClient.plans

		$("#m-new-handUp_step02 .org-name").html(CurrentClient.full_name)
		$("#m-new-handUp_step02 .onDuty-number").html(CurrentClient.duty_phone_1)

		//多个电话时，显示更多
		if(CurrentClient.duty_phone_2 || CurrentClient.duty_phone_3) {
			var duty_phone = CurrentClient.duty_phone_1;
			if(CurrentClient.duty_phone_2) {
				duty_phone = duty_phone + "," + CurrentClient.duty_phone_2
			}
			if(CurrentClient.duty_phone_3) {
				duty_phone = duty_phone + "," + CurrentClient.duty_phone_3
			}
			$(".onDuty-more").attr("title", duty_phone)
			$(".onDuty-more").show()
		} else {
			$(".onDuty-more").hide()
		}

		$.each(plans, function() {
			OLi += `<li>
			<div class='plan-radio'>
			<input type='radio' name='mnPlan' value='` + this.id + `' id='mnPlan` + this.id + `' />
			<label class='plan-label' for='mnPlan` + this.id + `'>&nbsp;</label>
			</div>
			<div class='plan-span'>
			<span>` + this.plan_title + `</span>
			</div>
			</li>`;
		});
		mnPlansUl.html(OLi);

	});

	Modal.hide("#m-new-handUp_step01", function() {
		Modal.show("#m-new-handUp_step02")
	});
}

function getCurrentClient() {
	for(var i = 0; i < clients.clientList.length; i++) {
		if($("input[name='mnOrg']:checked").eq(0).val() == clients.clientList[i].id) {
			return clients.clientList[i]
		}
	}
	return false
}

//上一步
YX.fn.lastStep = function() {
	Modal.hide("#m-new-handUp_step02", function() {
		Modal.show("#m-new-handUp_step01");
	});
}


YX.fn.newHandUpSubmit = function() {
	//校验
	var that  = this
	if($("input[name='mnPlan']:checked").length < 1){
		$("#mn-step02-remind").removeClass("hideDiv")
		return false
	}
	
	console.log($("input[name='mnOrg']:checked").eq(0).val())
	var param = {
		org_id:$("input[name='mnOrg']:checked").eq(0).val(),
		plan_id:$("input[name='mnPlan']:checked").eq(0).val()
	}

postAsk("http://127.0.0.1:6011/elcs/api/v1/emergency_report/ext/insert",param).then(function(data){
		that.mysdk.getTeam(data.data.group_id, function(error, obj) {
			that.cache.addTeam(obj)
			that.buildTeams()
			$('#teamsWrap .j-advanceTeam li[data-account="' + obj.teamId + '"]').click()
		})
	},function(err){
		alert("新建上报失败:"+err)
	}).then(function(){
		//隐藏新建上报模态框
		Modal.hide("#m-new-handUp_step02")
	})

}

function postAsk(url,paramters){
	return new Promise(function(resolve,reject){
		let param = paramters
		console.log(param)
		$.ajax({
			type:"post",
			url:url,
			contentType: "application/json; charset=utf-8",
			data:JSON.stringify(param),
			success:function(result){
				resolve(result)
			},
			error:function(err){
				reject(err)
			}
		});
	})
}

//点击确认按钮,新建上报
YX.fn.newHandUpSure = function() {
	var that = this
	if($("input[name='mnPlan']:checked").length < 1) {
		$("#mn-step02-remind").removeClass("hideDiv");
		return false;
	}



	var members = [];
	var names = [];
	var teamId = this.addTeamMemberTag && this.crtSessionAccount;
	var custom = {
		team_type: 0,
		plan_id: $("input[name='mnPlan']:checked").eq(0).val()
	};

	members.push("org_" + $("input[name='mnOrg']:checked").eq(0).val());
	members.push(readCookie('uid'));

	var parma = {
		org_id: $("input[name='mnOrg']:checked").eq(0).val(),
		plan_id: $("input[name='mnPlan']:checked").eq(0).val(),
		owner: "web_2",
		members: ['web_im', "web_2"],
		custom: {
			team_type: 0,
			plan_id: $("input[name='mnPlan']:checked").eq(0).val()
		}
	}

	$.ajax({
		url: "http://127.0.0.1:6011/elcs/api/v1/emergency_report/ext/insertEmergency_report",
		type: "post",
		data: JSON.stringify(parma),
		contentType: "application/json; charset=utf-8",
		success: function(result) {
			that.mysdk.getTeam(result.data.tid, function(error, obj) {
				that.cache.addTeam(obj)
				that.buildTeams()
				$('#teamsWrap .j-advanceTeam li[data-account="' + obj.teamId + '"]').click()
			})
			console.log(result);
		},
		error: function() {
			alert("请求出错");
		}
	}).then(function() {
		//隐藏新建上报模态框
		Modal.hide("#m-new-handUp_step02")
	});

}

var clients = {
	clientList: [],
	currentClient: {}
}

//点击新建上报按钮
YX.fn.newHandUp = function() {
	var that = this
	$("#m-new-handUp_step01").load("../zdy-view/newhandUp_step01.html", function() {
		//获得所有含有预案的指挥端
		$.ajax({
			url: "http://127.0.0.1:6011/elcs/api/v1/org/ext/getAllClientAndPlans",
			type: "get",
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				var mnOrgsUl = $("#mn-orgs-ul")
				var OLi = ""
				clients.clientList = result.data
				clients.currentClient = {}
				$.each(clients.clientList, function(i) {
					OLi += `<li>
					<div class='orgs-radio'>
					<input type='radio' name='mnOrg' value='` + this.id + `' id='mnOrg` + this.id + `' />
					<label class='orgs-label' for='mnOrg` + this.id + `'>&nbsp;</label>
					</div>
					<div class='orgs-span'>
					<span>` + this.full_name + `</span>
					</div>
					</li>`
				});
				mnOrgsUl.html(OLi)
			},
			error: function() {
				alert("请求出错")
			}
		});

		that.$mNextStep = $("#m-nextStep")
		that.$mNextStep.on('click', that.nextStep.bind(that))

		Modal.show("#m-new-handUp_step01")
	});
}

//点击新建上报按钮
/*YX.fn.newHandUp = function() {
	var that = this
	$("#m-new-handUp_step01").load("../zdy-view/newhandUp_step01.html", function() {
		//获得所有含有预案的指挥端
		$.ajax({
			url: "http://127.0.0.1:6011/elcs/api/v1/org/ext/getAllClientHasPlan",
			type: "get",
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				var mnOrgsUl = $("#mn-orgs-ul")
				var OLi = ""
				$.each(result.data, function(i, obj) {

					OLi += `<li>
						<div class='orgs-radio'>
							<input type='radio' name='mnOrg' value='` + obj.id + `' id='mnOrg` + obj.id + `' />
							<label class='orgs-label' for='mnOrg` + obj.id + `'>&nbsp;</label>
						</div>
						<div class='orgs-span'>
							<span>` + obj.full_name + `</span>
						</div>
					</li>`
				});
				mnOrgsUl.html(OLi)
			},
			error: function() {
				alert("请求出错")
			}
		});

		that.$mNextStep = $("#m-nextStep")
		that.$mNextStep.on('click', that.nextStep.bind(that))

		Modal.show("#m-new-handUp_step01")
	});
}*/

//zdy方法创建群组
YX.fn.zdyCreateTeam = function() {
	var accounts = [];
	var names = [];
	var teamId = this.addTeamMemberTag && this.crtSessionAccount;
	var that = this;
	var custom = {
		team_type: 0,
		plan_id: $("input[name='mnPlan']:checked").eq(0).val()
	};

	accounts.push("org_" + $("input[name='mnOrg']:checked").eq(0).val());
	accounts.push(readCookie('uid'));
	var owner = this.cache.getUserById(userUID).nick;
	names = [owner].concat(names).join('、').slice(0, 20)
		//隐藏新建上报模态框
		Modal.hide("#m-new-handUp_step02")
	}

	YX.fn.zdyPerson = function() {
	//console.log("teamId++"+teamId)
	var content = {
		type: 5,
		data: {
			user_name: "chenjie",
			phone_no: "1382182828",
			avatar_url: "…"
		}
	};
	this.mysdk.sendCustomMessage("team", "13319770", content, this.sendMsgDone.bind(this));
}